package com.tobby.camel.camelinaction.chapter3.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.dataformat.csv.CsvDataFormat;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class CustomOrderCsv extends CamelTestSupport {

	@Override
	public RouteBuilder createRouteBuilder() {
		return new RouteBuilder() {

			@Override
			public void configure() throws Exception {
				/*
				 * For version before 2.15.0, like 2.14.4 CSVConfig config = new
				 * CSVConfig(); config.setDelimiter(';'); config.setEndTrimmed(true);
				 * config.addField(new CSVField("name")); config.addField(new
				 * CSVField("customerId")); config.addField(new CSVField("amount"));
				 */
				CsvDataFormat myCsv = new CsvDataFormat();
				myCsv.setDelimiter(';');
				myCsv.setHeader(new String[] { "amount", "name", "price" });
				myCsv.setUseMaps(true);
				// myCsv.setRecordConverter(new MyConverter());
				// myCsv.setIgnoreSurroundingSpaces(false);
				from("direct:toCsv").marshal(myCsv)
						.to("file://target/orders/received?fileName=report-result.csv");
				from("file://target/orders/received?fileName=input.txt&noop=true")
						.unmarshal(myCsv).to("mock:result");
			}
		};
	}

	@Test
	public void testCsv() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<>();
		map.put("name", "            Camel in action                ");
		map.put("price", " 223.99");
		map.put("amount", "123 ");
		list.add(map);
		template.sendBody("direct:toCsv", list);

		MockEndpoint endpoint = getMockEndpoint("mock:result");
		List<?> list2 = endpoint.getExchanges().get(0).getIn().getBody(List.class);
		System.out.println(list2);
	}
}
